import {
  Controller,
  UseGuards,
  Post,
  Req,
  Body,
  HttpException,
  Get,
  HttpCode,
  Query
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

import { TeamDto } from './dto/team.dto';
import { RequestUser } from '../common/interfaces/request.interface';
import { TeamService } from './team.service';
import { ApiUseTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { ApiResult } from '@/common/interceptors/result.interceptor';

@ApiUseTags('团队模块')
@ApiBearerAuth()
@Controller('team')
@UseGuards(AuthGuard())
export class TeamController {
  constructor(private readonly teamService: TeamService) {}

  /**
   * 创建一个团队
   * @param req
   * @param param
   */
  @Post('insert-team')
  @ApiOperation({
    title: '创建团队',
    description: '用于用户创建一个团队'
  })
  @HttpCode(200)
  async createTeam(@Req() req: RequestUser, @Body() param: TeamDto) {
    const user = req.user;
    const oldTeam = await this.teamService.findTeamByTeamName(param.teamName);
    if (oldTeam) {
      return new ApiResult('', '已经存在的团队了', false);
    }
    const team = {
      userId: user._id,
      teamName: param.teamName,
      status: 1,
      type: 1
    };
    await this.teamService.createTeam(team);

    return new ApiResult('');
  }

  @Get('list')
  @ApiOperation({
    title: '查询团队列表',
    description: '查询当前用户所拥有的团队'
  })
  async searchTeamList(@Req() req: RequestUser) {
    const data = await this.teamService.findTeamList(req.user._id);
    return new ApiResult(data);
  }

  @Get('change-team')
  @ApiOperation({
    title: '切换使用的团队',
    description: '切换激活的团队'
  })
  async changeTeam(@Req() req: RequestUser, @Query('id') id: string) {
    await this.teamService.changeTeam(req.user._id, id);
    return new ApiResult('');
  }

  @Get('delete-team')
  @ApiOperation({
    title: '退出团队',
    description: '退出自建或加入的团队'
  })
  async deleteTeam(@Query('id') id: string) {
    await this.teamService.deleteTeam(id);
    return new ApiResult('');
  }
}
